package il.technion.cs236369.webserver.handlers;

import il.technion.cs236369.webserver.components.IDataHandler;
import il.technion.cs236369.webserver.components.INewWebRequest;
import il.technion.cs236369.webserver.components.ServerUtils;
import il.technion.cs236369.webserver.configuration.IServerConfiguration;
import il.technion.cs236369.webserver.simpleServlets.ISimpleServlet;

import java.io.IOException;

import org.apache.http.HttpServerConnection;

/**
 * This class handles new web requests coming from the request queue.
 * @author Ofir Haviv and Itamar Talmi
 *
 */
public class WebRequestHandler implements IDataHandler<INewWebRequest> {

	private IServerConfiguration serverConfiguration;
	private IFileSystemHandler fileSystemHandler;
	
	/**
	 * The constructor of the NewWebRequestHandler class.
	 * @param serverConfiguration - The configuration of the server.
	 * @param baseDir - The base directory of the server.
	 * @param WelcomFile - The file to be return when asked for path "/"
	 */
	public WebRequestHandler(IServerConfiguration serverConfiguration, String baseDir, String WelcomFile){
		this.serverConfiguration = serverConfiguration;
		fileSystemHandler = new FileSystemHandler(serverConfiguration, baseDir, WelcomFile);
	}
	
	@Override
	public void handleData(INewWebRequest newRequest) {
		
		String relativePath = newRequest.getRequestedPath();
		ISimpleServlet neddedServlet = serverConfiguration.getServlet(relativePath);
		if (neddedServlet != null){
			//TODO: Call the servlet
		}
		else
			fileSystemHandler.handleRequest(newRequest);
		
	//	ServerUtils.sendInternalServerError(newRequest.getClientConnection());
		HttpServerConnection connection = newRequest.getClientConnection();
		if (connection.isOpen()) 
			ServerUtils.sendInternalServerError(connection);
		
		////////////////////////////////////////////////
		////	Temp... Returning constant response ////
		////////////////////////////////////////////////
	/*	HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1,
        		HttpStatus.SC_OK ,
        		EnglishReasonPhraseCatalog.INSTANCE.getReason(HttpStatus.SC_OK, Locale.ENGLISH));
		try {
			response.setEntity(new StringEntity("I am the king!!!"));
		} catch (UnsupportedEncodingException e) {
			// Should never happend.
			e.printStackTrace();
		}
		
		HttpServerConnection connection = newRequest.getClientConnection();
		try {
			connection.sendResponseHeader(response);
			connection.sendResponseEntity(response);
		} catch (HttpException | IOException e) {
			
			e.printStackTrace();
		}
		
		try { connection.close(); } catch (IOException e) {	}
		
	//	System.out.println("New Web Request Arrived");*/
		
	}

}
